<script setup>
import { onMounted, ref, nextTick } from "vue";
import { Edit, Delete, View, CloseBold, Unlock } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import axios from "axios";
import { SrtingToNum, levelSrtingToNum } from "@/utils/typeMap";
import {
  getRole,
  getRoleMenuList,
  getRoleMenus,
  PutRoleMenus,
  postBanRole,
  postEnableRole,
  postAddRole,
} from "@/api/permission";
import { add, get } from "lodash";

const total = ref(0);
const pagenum = ref(1);
const pagesize = ref(7);

const roleList = ref([]); //全部角色
const sysMenu = ref([]); //系统菜单
const getRoleList = async () => {
  const res = await getRole();
  // console.log("res", res);
  roleList.value = res.data;
};

const sizeChange = async () => {
  //页面发生变化
  getRoleList();
};
onMounted(() => {
  getRoleList();
  // console.log("角色", roleList);
  getMenu();
  // console.log("菜单", sysMenu);
});

const dialogVisible = ref(false);

const RoleFormRef = ref();
const roleform = ref({
  roleName: "", //英文字段
  description: "", //角色描述
  isDefault: "", //是否为默认
  isAvailable: "", //是否可用
  menuIdList: [], //权限列表，也做复选框,addRoleMenuList
});
const RoleFormrules = ref({
  roleName: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    {
      pattern: /^[a-zA-Z]+$/, //必须是英文，数据库是那么建立的
      message: "请输入英文字段",
    },
  ],
  description: [
    { required: true, message: "请输入角色描述(中文名称)", trigger: "blur" },
  ],
  isDefault: [
    { required: true, message: "请选择是否为默认角色", trigger: "blur" },
  ],
  isAvailable: [{ required: true, message: "请选择是否可用", trigger: "blur" }],
  menuIdList: [{ required: true, message: "请选择权限", trigger: "blur" }],
});

const handleClose = async () => {
  dialogVisible.value = false;
  RoleVisible.value = false;
  isCheckList.value = [];
  //移除isCheckList的值
  roleID.value = "";
  roleform.value = {};
  checkStrictly.value = true;
  AddcheckStrictly.value = true;
  nextTick(() => {
    // 显示弹窗
    if (tree.value) {
      tree.value.setCheckedKeys([]); // 清除所有选中状态
    }
    if (addtree.value) {
      addtree.value.setCheckedKeys([]);
    }
  });
};

const BanRole = async (roleId) => {
  const res = await postBanRole(roleId);
  if (res.code) {
    ElMessage.error("禁用失败");
    return;
  }
  ElMessage.success("禁用成功");
  getRoleList();
};
const EnableRole = async (roleId) => {
  const res = await postEnableRole(roleId);
  if (res.code) {
    ElMessage.error("启用失败");
    return;
  }
  ElMessage.success("启用成功");
  getRoleList();
};

let isCheckList = ref([]); //角色菜单
const RoleVisible = ref(false);

const tree = ref(); //树形的选择器
const defaultProps = {
  children: "children",
  label: "label",
  //path里包含/permission开头的，就禁用
  disabled: (item) => {
    return item.path.indexOf("/permission") !== -1;
  },
}; //树形组件要用这个现实label
const checkStrictly = ref(true);
const AddcheckStrictly = ref(true);
const BeforeAddRole = async () => {
  dialogVisible.value = true;
  nextTick(() => {
    AddcheckStrictly.value = false;
  });
};

const addtree = ref(); //就是为了获取权限的
const addRole = async () => {
  //首先处理menuIdList
  let arr = addtree.value.getCheckedKeys();
  console.log("arr", arr);
  //半选的ID
  let arr1 = addtree.value.getHalfCheckedKeys();
  console.log("arr1", arr1);
  roleform.value.menuIdList = arr.concat(arr1);
  console.log("roleform.menuIdList", roleform.value.menuIdList);
  const res = await postAddRole(roleform.value);
  if (res.code) {
    ElMessage.error("添加角色失败");
    return;
  }
  ElMessage.success("添加角色成功,请重新登陆获取权限");
  handleClose();
  getRoleList();
};

const roleID = ref(); //这里存一个id,因为打开弹窗后需要这个值

const BeforEditRoleMenu = async (roleId) => {
  //获得用户角色
  //   isCheckList.value = [0, 1, 2];
  isCheckList.value = [];
  console.log("谁的权限", roleId);
  const res = await getRoleMenus(roleId);
  if (res.code) {
    ElMessage.error("角色权限获取失败");
    return;
  }
  isCheckList.value = res.data;
  // console.log("角色ID", roleID);
  // console.log("角色权限", res.data);
  // console.log("check", isCheckList.value);
  roleID.value = roleId;
  RoleVisible.value = true;
  //等数据加载完，才置为false
  nextTick(() => {
    checkStrictly.value = false;
  });
};

const getMenu = async () => {
  const res = await getRoleMenuList();
  if (res.code) {
    ElMessage.error("菜单获取失败");
    return;
  }
  ElMessage.success("菜单获取成功");
  sysMenu.value = res.data;
  // console.log("res", res.data);
  //把id为12，label为权限管理的手动过滤掉
  // sysMenu.value = sysMenu.value.filter((item) => item.id != 12);
  // console.log("sysMenu", sysMenu.value);
};

const EditRole = async () => {
  let arr = tree.value.getCheckedKeys();
  // console.log("arr", arr);
  //半选的ID
  let arr1 = tree.value.getHalfCheckedKeys();
  // console.log("arr1", arr1);
  let permissionId = arr.concat(arr1);
  // console.log("修改角色", permissionId);
  const res = await PutRoleMenus(roleID.value, permissionId);
  if (res.code) {
    ElMessage.error("角色权限修改失败");
    return;
  }
  ElMessage.success("角色权限修改成功，请重新登录获取权限");
  handleClose();
};
</script>

<template>
  <el-card class="box">
    <div class="top">
      <span style="font-size: 25px; color: #203857">权限管理</span>
      <el-button type="success" @click="BeforeAddRole" plain
        ><el-icon><ElementPlus /></el-icon>添加角色</el-button
      >
    </div>
    <el-table :data="roleList" height="300px" stripe>
      <el-table-column
        type="index"
        label="序号"
        width="55"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="roleDescription"
        label="用户角色"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center">
        <template #="{ row }">
          <el-button
            title="更改权限"
            type="success"
            size="small"
            text
            link
            plain
            @click="BeforEditRoleMenu(row.roleId)"
            >更改权限</el-button
          >
          <el-button
            title="启用角色"
            type="primary"
            size="small"
            text
            link
            plain
            :disabled="row.isAvailable == 1"
            @click="EnableRole(row.roleId)"
            >启用</el-button
          >
          <el-popconfirm
            :title="`确定禁用角色吗？`"
            width="250px"
            icon="Delete"
            @confirm="BanRole(row.roleId)"
          >
            <template #reference>
              <el-button
                title="禁用角色"
                plain
                type="danger"
                size="small"
                text
                link
                :disabled="row.isAvailable != 1"
                >禁用</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
        @size-change="sizeChange"
        @current-change="getRoleList"
        :pager-count="9"
        v-model:current-page="pagenum"
        v-model:page-size="pagesize"
        :page-sizes="[3, 5, 7, 9, 15, 30, 60]"
        :background="true"
        layout="prev, pager, next, jumper,->,sizes,total"
        :total="total"
      />
    </div>

    <el-dialog v-model="dialogVisible" width="600" :before-close="handleClose">
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">添加角色</span>
        </div>
      </template>
      <el-form
        :model="roleform"
        label-width="auto"
        :rules="RoleFormrules"
        ref="RoleFormRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleform.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleform.description" />
        </el-form-item>
        <el-form-item label="角色默认" prop="isDefault">
          <el-radio-group v-model="roleform.isDefault">
            <el-radio :label="1">默认角色</el-radio>
            <el-radio :label="0">非默认角色</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色禁用" prop="isAvailable">
          <el-radio-group v-model="roleform.isAvailable">
            <el-radio :label="1">可用</el-radio>
            <el-radio :label="0">不可用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色权限" prop="menuIdList">
          <template #default>
            <el-tree
              ref="addtree"
              :data="sysMenu"
              show-checkbox
              node-key="id"
              default-expand-all
              :props="defaultProps"
              :check-strictly="AddcheckStrictly"
            >
              <!-- 树形控件.复选框，key是id,默认展开，默认勾选的 -->
              <!-- 数据就是menuArr符合树形控件 -->
              <!-- prop是展示值的，和table里的一样，tree用来存储值 -->
            </el-tree>
          </template>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button text link @click="handleClose">取消</el-button>
          <el-button type="primary" text link @click="addRole">
            确认添加
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-drawer
      direction="ltr"
      v-model="RoleVisible"
      :before-close="handleClose"
    >
      <template #header="{}">
        <div class="my-header">
          <img class="imgtitle" src="@/assets/images/logo.jpg" />
          <span class="titleClass">更改角色权限</span>
        </div>
      </template>
      <!-- 根据roleList显示复选框，v-model绑定ischekList[i] ,roleID为0和2 要禁用-->
      <template #default>
        <el-tree
          ref="tree"
          :data="sysMenu"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="isCheckList"
          :props="defaultProps"
          :check-strictly="checkStrictly"
        >
          <!-- 树形控件.复选框，key是id,默认展开，默认勾选的 -->
          <!-- 数据就是menuArr符合树形控件 -->
          <!-- prop是展示值的，和table里的一样，tree用来存储值 -->
        </el-tree>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button text link @click="handleClose">取消</el-button>
          <el-button type="primary" text link @click="EditRole">
            确认更改
          </el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<style scoped lang="scss">
.box {
  padding: 15px;
  // //开启相对定位
  // position: relative;
  // .el-pagination {
  //   position: absolute;
  //   bottom: 25px;
  // }
  .el-table {
    margin-bottom: 2vh;
  }
}
.top {
  display: flex;
  width: 100%;

  height: 50px;
  line-height: 50px;

  //垂直居中
  align-items: center;
  .el-button {
    margin-left: 20px;
  }
  margin-bottom: 15px;
}

.my-header {
  display: flex;
  height: 35px;
  line-height: 35px;
  .titleClass {
    font-size: 15px;
  }
  .imgtitle {
    width: 35px;
    height: 35px;
    margin-right: 10px;
  }
  .titleendClass {
    margin-left: 10px;
    font-size: 20px;
  }
}
</style>
